package com.chart.chart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chart.chart.domian.ChartConfigsAndViewsVo;
import com.chart.chart.domian.ChartViewsUser;
import com.chart.chart.domian.vo.ChartViewsUserPasswordVO;
import com.chart.chart.domian.vo.ChartViewsUserVO;
import com.chart.chart.domian.vo.ChartViewsVo;
import com.chart.chart.mapper.ChartViewsMapper;
import com.chart.chart.service.IChartViewsUserService;
import com.chart.common.constant.Constants;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.redis.RedisCache;
import com.chart.common.utils.uuid.IdUtils;
import com.chart.system.mapper.ChartThemeTypeMapper;
import com.chart.system.mapper.ChartViewsThemeMapper;
import com.chart.system.service.ChartThemeTypeService;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.impl.SysUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static com.chart.common.utils.PageUtils.startPage;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class CharViewsUserServiceImpl extends ServiceImpl<ChartViewsMapper, ChartViewsUser> implements IChartViewsUserService {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ChartViewsMapper chartViewsMapper;
    @Autowired
    private ChartViewsThemeMapper chartViewsThemeMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<ChartViewsVo> getList(ChartViewsVo chartViewsVo) {
        // startPage();
        List<ChartViewsVo> list = chartViewsMapper.getList(chartViewsVo);
        return list;
    }

    @Override
    public boolean scatterChartViewUser(List<ChartViewsUser> collect) {
        return chartViewsMapper.scatterChartViewUser(collect);
    }

    @Override
    public boolean updateViewTop(ChartViewsUser chartViewsUser) {
        return chartViewsMapper.updateViewTop(chartViewsUser);
    }


//    @Override
//    public ChartViewsUserVO queryChartViewById(Long id) {
//        // 校验ID是否为空
//        if (id == null) {
//            log.error("查询失败：id 不能为空！");
//            throw new IllegalArgumentException("id 不能为空");
//        }
//        // 查询ChartViewsUser对象
//        ChartViewsUser chartViewsUser = chartViewsMapper.selectById(id);
//
//        // 校验ChartViewsUser是否存在
//        if (chartViewsUser == null) {
//            log.warn("未找到ID为 {} 的ChartViewsUser对象", id);
//            return null;  // 或者根据需求抛出异常
//        }
//
//        // 获取用户ID并查询对应的SysUser
//        Long userId = chartViewsUser.getUserId();
//
//        // 校验userId是否存在
//        if (userId == null) {
//            log.error("ChartViewsUser对象的userId为空，ID为：{}", id);
//            throw new IllegalStateException("userId 不能为空");
//        }
//
//        // 查询SysUser对象
//        SysUser sysUser = sysUserService.selectUserById(userId);
//
//        // 校验SysUser是否存在
//        if (sysUser == null) {
//            log.warn("未找到ID为 {} 的SysUser对象", userId);
//            return null;  // 或者根据需求抛出异常
//        }
//
//        // 获取isVip字段并校验
//        Integer isVip = sysUser.getIsVip();
//        if (isVip == null) {
//            log.error("SysUser对象的isVip字段为空，userId为：{}", userId);
//            throw new IllegalStateException("isVip 字段不能为空");
//        }
//        // 创建ChartViewsUserVO对象并手动赋值isVip
//        ChartViewsUserVO chartViewsUserVO = new ChartViewsUserVO();
//        // 复制其他字段
//        BeanUtils.copyProperties(chartViewsUser, chartViewsUserVO);
//        // 手动设置isVip
//        chartViewsUserVO.setIsVip(isVip);
//        return chartViewsUserVO;
//    }



    @Override
    public ChartViewsUserVO queryChartViewById(Long id) {
        // 校验ID是否为空
        if (id == null) {
            log.error("查询失败：id 不能为空！");
            throw new IllegalArgumentException("id 不能为空");
        }

        // 查询ChartViewsUser对象
        ChartViewsUser chartViewsUser = chartViewsMapper.selectById(id);

        // 校验ChartViewsUser是否存在
        if (chartViewsUser == null) {
            log.warn("未找到ID为 {} 的ChartViewsUser对象", id);
            return null; // 或者根据需求抛出异常
        }

        // 获取用户ID并查询对应的SysUser
        Long userId = chartViewsUser.getUserId();

        // 校验userId是否存在
        if (userId == null) {
            log.error("ChartViewsUser对象的userId为空，ID为：{}", id);
            throw new IllegalStateException("userId 不能为空");
        }

        // 查询SysUser对象
        SysUser sysUser = sysUserService.selectUserById(userId);

        // 校验SysUser是否存在
        if (sysUser == null) {
            log.warn("未找到ID为 {} 的SysUser对象", userId);
            return null; // 或者根据需求抛出异常
        }

        // 获取isVip字段并校验
        Integer isVip = sysUser.getIsVip();
        if (isVip == null) {
            log.error("SysUser对象的isVip字段为空，userId为：{}", userId);
            throw new IllegalStateException("isVip 字段不能为空");
        }

        // 查询主题色信息
        Integer viewsThemeId = chartViewsUser.getViewsThemeId();
        com.example.entity.ChartViewsTheme chartViewsTheme = null;
        if (viewsThemeId != null) {
            chartViewsTheme = chartViewsThemeMapper.selectById(viewsThemeId);
        }

        // 创建ChartViewsUserVO对象并赋值
        ChartViewsUserVO chartViewsUserVO = new ChartViewsUserVO();
        BeanUtils.copyProperties(chartViewsUser, chartViewsUserVO);

        // 设置isVip字段
        chartViewsUserVO.setIsVip(isVip);

        // 设置screenTheme字段
        if (chartViewsTheme != null) {
            // 解决匿名内部类中的变量访问问题
            final com.example.entity.ChartViewsTheme finalChartViewsTheme = chartViewsTheme;
            chartViewsUserVO.setScreenTheme(new HashMap<String, Object>() {{
                put("id", finalChartViewsTheme.getId());
                put("name", finalChartViewsTheme.getThemeName());
                put("color", Arrays.asList(finalChartViewsTheme.getThemeColors().split(",")));
            }});
        } else {
            chartViewsUserVO.setScreenTheme(null); // 如果没有主题信息，设置为null或者默认值
        }

        return chartViewsUserVO;
    }







    @Override
    public AjaxResult updateViewById(Long id, Integer openShare, Integer accessCheck, String password) {
        String targetValue = String.valueOf(id);
        // 获取所有以 "tokens:" 开头的键
        Collection<String> keysCollection = redisCache.keys("tokens:*"); // 返回的是 Collection<String>
        Set<String> keys = new HashSet<>(keysCollection); // 转换为 Set<String>
        // 遍历所有键并删除值为目标ID的缓存
        for (String key : keys) {
            Object value = redisCache.getCacheObject(key);
            if (value != null && value.toString().equals(targetValue)) {
                redisCache.deleteObject(key); // 删除键
            }
        }


        // 根据ID查找记录
        ChartViewsUser chartViewsUser = chartViewsMapper.selectById(id);
        if (ObjectUtils.isEmpty(chartViewsUser)) {
            return AjaxResult.error(570, "未查询到该大屏信息");
        }
        // 设置需要更新的字段值
        chartViewsUser.setOpenShare(openShare);
        chartViewsUser.setAccessCheck(accessCheck);

        // 对密码进行BCrypt哈希处理
        // String hashedPassword = hashPassword(password);
        chartViewsUser.setPassword(password);
        // 设置 expirationTime 为当前时间加一年，并转换为 Date 类型
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expirationTime = now.plus(1, ChronoUnit.YEARS);
        Date expirationDate = Date.from(expirationTime.atZone(ZoneId.systemDefault()).toInstant());
        chartViewsUser.setExpirationTime(expirationDate);
        // 执行更新操作
        int updateResult = chartViewsMapper.updateById(chartViewsUser);
        if (updateResult > 0) {
            return AjaxResult.success("更新成功", chartViewsUser);
        } else {
            return AjaxResult.error(572, "更新操作失败");
        }
    }


//    @Override
//    public ChartViewsUserPasswordVO queryChartViewPasswordById(Long id) {
//        ChartViewsUser chartViewsUser = chartViewsMapper.selectById(id);
//
//
//        ChartViewsUserPasswordVO chartViewsUserVO = new ChartViewsUserPasswordVO();
//
//        BeanUtils.copyProperties(chartViewsUser, chartViewsUserVO);
//
//        return chartViewsUserVO;
//    }


    @Override
    public ChartViewsUserPasswordVO queryChartViewPasswordById(Long id) {
        // 查询ChartViewsUser对象
        ChartViewsUser chartViewsUser = chartViewsMapper.selectById(id);

        // 校验ChartViewsUser是否存在
        if (chartViewsUser == null) {
            log.warn("未找到ID为 {} 的ChartViewsUser对象", id);
            return null; // 或者根据需求抛出异常
        }

        // 创建ChartViewsUserPasswordVO对象
        ChartViewsUserPasswordVO chartViewsUserVO = new ChartViewsUserPasswordVO();
        BeanUtils.copyProperties(chartViewsUser, chartViewsUserVO);

        // 查询主题色信息
        Integer viewsThemeId = chartViewsUser.getViewsThemeId();
        com.example.entity.ChartViewsTheme chartViewsTheme = null;
        if (viewsThemeId != null) {
            chartViewsTheme = chartViewsThemeMapper.selectById(viewsThemeId);
        }

        // 设置screenTheme字段
        if (chartViewsTheme != null) {
            final com.example.entity.ChartViewsTheme finalChartViewsTheme = chartViewsTheme;
            chartViewsUserVO.setScreenTheme(new HashMap<String, Object>() {{
                put("id", finalChartViewsTheme.getId());
                put("name", finalChartViewsTheme.getThemeName());
                put("color", Arrays.asList(finalChartViewsTheme.getThemeColors().split(",")));
            }});
        } else {
            chartViewsUserVO.setScreenTheme(null); // 如果没有主题信息，设置为null或者默认值
        }

        return chartViewsUserVO;
    }



    // 方法用于将字符串转换为MD5哈希
    private String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(password.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
